package org.zxt.web.buss.config;

import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;
import java.util.Locale;
import java.util.Map;

public class Conf extends JSONObject {
    public Conf(Map<String,Object> map) {
        super(map);
    }

    public <T> T getWithPrefix(String prefix, Class<T> clazz) {
        if(!prefix.endsWith(".")){
            prefix += ".";
        }
        String finalPrefix = prefix;
        try {
            if(clazz.isAssignableFrom(Map.class)){
                T obj = clazz.newInstance();
                this.forEach((key, value) -> {
                    if(key.startsWith(finalPrefix)){
                        ((Map<String, Object>) obj).put(key.substring(0, finalPrefix.length()), value);
                    }
                });
                return obj;
            } else {
                JSONObject map = new JSONObject();
                this.forEach((key, value) -> {
                    if(key.startsWith(finalPrefix)){
                        String simpleField = key.substring(finalPrefix.length());
                        processKeyVal(map, simpleField, value);
                    }
                });
                return JSONObject.toJavaObject(map, clazz);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void processKeyVal(JSONObject map, String simpleField, Object value) {
        if(simpleField.contains(".")) {
            String key = convertToJavaFiled(simpleField.substring(0, simpleField.indexOf(".")));
            map.compute(key, (k,v)->{
                JSONObject obj = new JSONObject();
                map.put(key, obj);
                processKeyVal(obj, simpleField.substring(simpleField.indexOf(".")+1), value);
                return obj;
            });
        } else {
            map.put(convertToJavaFiled(simpleField), value);
        }
    }

    private String convertToJavaFiled(String simpleField) {
        if(!simpleField.contains("-")){
            return simpleField;
        }
        String str = Arrays.asList(simpleField.split("-"))
                .stream()
                .filter(item->item != null && item.trim().length() > 0)
                .reduce(new StringBuilder(), (sb, item)->{
                    if(sb.length() > 0){
                        sb.append(String.valueOf(item.charAt(0)).toUpperCase(Locale.ROOT)).append(item.substring(1));
                    } else {
                        sb.append(item);
                    }
                    return sb;
                }, (sb, sb1)->{
                    sb.append(sb1);
                    return sb;
                }).toString();
        return str;
    }
}
